#!/usr/bin/env python3
###
# @Author: Logan.Li
# @Gitee: https://gitee.com/attacker
# @email: admin@attacker.club
# @Date: 2025-03-14 08:50:30
# @LastEditTime: 2025-03-14 08:50:35
# @Description: 阿里云RDS监控模块
###

import os
import json
import logging
from typing import Dict, List
from aliyunsdkrds.request.v20140815 import DescribeDBInstancesRequest
from ..core import AliyunMonitorBase

class RDSMonitor(AliyunMonitorBase):
    """RDS数据库监控"""
    
    def __init__(self, config: Dict):
        super().__init__(config)
        self.namespace = "acs_rds_dashboard"
        
    def list_instances(self) -> List[Dict]:
        """获取RDS实例列表"""
        try:
            request = DescribeDBInstancesRequest.DescribeDBInstancesRequest()
            response = self.client.do_action_with_exception(request)
            return json.loads(response).get('Items', {}).get('DBInstance', [])
        except Exception as e:
            logging.error(f"获取RDS实例列表失败: {e}")
            return []
            
    def setup_instance_monitoring(self, instance_id: str, instance_name: str):
        """设置实例监控
        
        Args:
            instance_id: 实例ID
            instance_name: 实例名称
        """
        dimensions = [{"instanceId": instance_id}]
        
        # CPU使用率告警
        self.create_alarm_rule(
            rule_name=f"{instance_name}-CPU使用率告警",
            namespace=self.namespace,
            metric_name="CpuUsage",
            dimensions=dimensions,
            threshold=float(self.config['thresholds']['cpu']),
            contact_groups=self.config['contact_groups']
        )
        
        # 内存使用率告警
        self.create_alarm_rule(
            rule_name=f"{instance_name}-内存使用率告警",
            namespace=self.namespace,
            metric_name="MemoryUsage",
            dimensions=dimensions,
            threshold=float(self.config['thresholds']['memory']),
            contact_groups=self.config['contact_groups']
        )
        
        # IOPS使用率告警
        self.create_alarm_rule(
            rule_name=f"{instance_name}-IOPS使用率告警",
            namespace=self.namespace,
            metric_name="IOPSUsage",
            dimensions=dimensions,
            threshold=float(self.config['thresholds']['iops']),
            contact_groups=self.config['contact_groups']
        )
        
        # 连接数使用率告警
        self.create_alarm_rule(
            rule_name=f"{instance_name}-连接数使用率告警",
            namespace=self.namespace,
            metric_name="ConnectionUsage",
            dimensions=dimensions,
            threshold=float(self.config['thresholds']['connection']),
            contact_groups=self.config['contact_groups']
        )
        
        # 磁盘空间使用率告警
        self.create_alarm_rule(
            rule_name=f"{instance_name}-磁盘空间使用率告警",
            namespace=self.namespace,
            metric_name="DiskUsage",
            dimensions=dimensions,
            threshold=float(self.config['thresholds']['disk']),
            contact_groups=self.config['contact_groups']
        )
        
    def get_instance_metrics(self, instance_id: str) -> Dict:
        """获取实例的监控指标
        
        Args:
            instance_id: 实例ID
        """
        dimensions = [{"instanceId": instance_id}]
        metrics = {}
        
        metric_list = [
            ("CpuUsage", "cpu"),
            ("MemoryUsage", "memory"),
            ("IOPSUsage", "iops"),
            ("ConnectionUsage", "connection"),
            ("DiskUsage", "disk")
        ]
        
        for metric_name, key in metric_list:
            data = self.get_metric_data(
                namespace=self.namespace,
                metric_name=metric_name,
                dimensions=dimensions
            )
            metrics[key] = data
            
        return metrics
        
    def monitor_all_instances(self):
        """监控所有RDS实例"""
        instances = self.list_instances()
        for instance in instances:
            instance_id = instance['DBInstanceId']
            instance_name = instance.get('DBInstanceDescription', instance_id)
            self.setup_instance_monitoring(instance_id, instance_name)
            logging.info(f"已设置实例监控: {instance_name}")

# 使用示例
if __name__ == "__main__":
    # 配置示例
    config = {
        "access_key": "your_access_key",
        "secret_key": "your_secret_key",
        "region": "cn-hangzhou",
        "thresholds": {
            "cpu": 80,
            "memory": 85,
            "iops": 80,
            "connection": 80,
            "disk": 85
        },
        "contact_groups": ["default"],
        "notification": {
            "dingtalk": {
                "enabled": True,
                "webhook": "your_webhook_url",
                "secret": "your_secret"
            },
            "lark": {
                "enabled": True,
                "webhook": "your_webhook_url"
            }
        }
    }
    
    monitor = RDSMonitor(config)
    
    # 监控所有实例
    monitor.monitor_all_instances()
    
    # 获取特定实例的指标
    metrics = monitor.get_instance_metrics("your_instance_id")
    print(json.dumps(metrics, indent=2))
